import React from 'react'
import {
  BrowserRouter as Router,
  Route,
  Link,
  withRouter
} from 'react-router-dom'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as userInfoActionsFromOtherFile from '../../../actions/userinfo'
import * as storeActionsFromOtherFile from '../../../actions/store'
import BuyAndStore from "../../../components/BuyAndStore";

class Buy extends React.Component {
  constructor(props, context){
    super(props, context);
    this.state = {
      isStore: false
    }
  }
  render(){
    return (
      <div>
        <BuyAndStore
          isStore={this.state.isStore}
          buyHandle={this.buyHandle.bind(this)}
          storeHandle={this.storeHandle.bind(this)}/>
      </div>
    );
  }
  componentDidMount(){
    // console.log(123, this.props.store);
    // console.log(456, this.props.storeActions);
    this.checkStoreState();
  }
  // 检验当前商户是否已经被收藏
  checkStoreState() {
    const id = this.props.id
    const store = this.props.store

    // some 即任何一个满足即可
    store.some(item => {
      if (item.id === id) {
        // 已经被收藏
        this.setState({
          isStore: true
        })
        // 跳出循环
        return true
      }
    })
  }
  // check login
  loginCheck(){
    const id = this.props.id;
    const userinfo = this.props.userinfo;
    if (!userinfo.username) {
      // 跳转到登录页面
      this.props.history.push('/login' + '/detail/' + encodeURIComponent(id));
      return false;
    }
    return true;
  }
  // buy event
  buyHandle(){
    // 验证登录，未登录则return
    const loginFlag = this.loginCheck();
    if (!loginFlag) {
      return
    }

    // 此过程为模拟购买，因此可省去复杂的购买过程
    // ...
    // ...
    // ...

    // 跳转到用户主页
    this.props.history.push('/User');
  }
  // store event
  storeHandle(){
    // 验证登录
    const loginFlag = this.loginCheck();
    if(!loginFlag){
      return
    }


    const id = this.props.id;
    const storeActions = this.props.storeActions;
    if(this.state.isStore){
      // 当前商户已经被收藏。点击时即要取消收藏
      storeActions.rm({id: id});
    } else {
      // 当前商户尚未被收藏。点击时即要执行收藏
      storeActions.add({id: id});
    }

    // 修改状态
    this.setState({
      isStore: !this.state.isStore
    });
  }
}

// -----------redux react 绑定 --------------
function mapStateToProps(state) {
  return {
    userinfo: state.userinfo,
    store: state.store

  }
}

function mapDispatchToProps(dispatch) {
  return {
    storeActions: bindActionCreators(storeActionsFromOtherFile, dispatch)
  }
}
export default withRouter(connect(
  mapStateToProps,
  mapDispatchToProps
)(Buy));

